import {
  getWorkOrderAuditList,
  getUserInfo
} from '/service/service'
import {
  getContainerHeight
} from '/utils/getDimensionUtil'
const {
  getCurrentStatusMap
} = require('/utils/statusMap')
Page({
  data: {
    searchHeight: 0,
    searchContent: {},

    hasMore: true,
    windowHeight: 0,
    isLoading: false,
    scrollTop: 0,
    scrollViewHeight: 0,
    showBackTop: false,
    loadLock: false, // 新增加载锁

    pageNum: 1,
    pageSize: 10,
    total: 0,
    currentTotal: 0,
    list: [],

    rangeKey: 0,
    fixRange: null,
    projectId: '',

    roles: [],
    exportRoles: ['superadmin', 'jianli', 'yezhu', 'baoan'],
    isShowCheckBtn: false,
  },
  onLoad() {
    getUserInfo().then(res => {
      const {
        roles
      } = res
      const {
        exportRoles
      } = this.data
      if (res && roles) {
        this.setData({
          roles,
          isShowCheckBtn: roles.some(role => exportRoles.includes(role))
        })
      }
    })
    this.getWindowHeight()
    this.getList()
  },
  onPageScroll(e) {
    const {
      scrollTop
    } = e
    const {
      windowHeight,
      scrollViewHeight,
      isLoading,
      hasMore,
      loadLock,
      total,
      list
    } = this.data

    this.setData({
      showBackTop: scrollTop > 300
    });

    // 基本条件判断：如果正在加载、没有更多数据、有加载锁或总数据为0，则不触发
    if (isLoading || !hasMore || loadLock || total === 0) return

    // 剩余高度 = 列表总高度 - 滚动距离 - 窗口高度
    const remainingDistance = scrollViewHeight - scrollTop - windowHeight

    // 当剩余距离小于50px且当前列表长度小于总条数时触发加载
    if (remainingDistance < 50 && list.length < total) {
      this.setData({
        loadLock: true
      }) // 锁定加载

      this.setData({
        pageNum: this.data.pageNum + 1
      }, () => {
        // 确保getList完成后再解锁
        this.getList().finally(() => {
          this.setData({
            loadLock: false
          })
        })
      })
    }

    this.setData({
      scrollTop
    })
  },
  onReady() {
    this.getSearchHeight()
    this.getWrapHeight()
  },
  onShow() {
    this.handleSearch()
  },
  onPullDownRefresh() {
    console.log('下拉刷新');
    this.setData({
      pageNum: 1,
      list: [],
      hasMore: true,
      loadLock: false // 重置加载锁
    }, async () => {
      try {
        await this.getList();
      } catch (e) {
        console.error('下拉刷新失败：', e);
      } finally {
        dd.stopPullDownRefresh();
      }
    });
  },
  getWindowHeight() {
    const systemInfo = my.getSystemInfoSync()
    this.setData({
      windowHeight: systemInfo.windowHeight
    })
    console.log('窗口高度:', this.data.windowHeight)
  },
  async getList() {
    if (this.data.isLoading || !this.data.hasMore) return
    const {
      pageNum,
      pageSize,
      searchContent
    } = this.data
    const params = {
      pageNum,
      pageSize,
      ...searchContent
    }
    console.log('请求参数:', params)
    try {
      this.setData({
        isLoading: true
      })
      const res = await getWorkOrderAuditList(params)
      const {
        rows,
        total
      } = res || {
        rows: [],
        total: 0
      }

      const newList = rows
        .filter(r => !this.data.list.some(old => old.id === r.id))
        .map(item => {
          return {
            ...item,
            currentStatusName: getCurrentStatusMap(item.status)
          }
        })

      const updateList = this.data.list.concat(newList)
      // 调整hasMore判断逻辑：只要当前列表长度小于总条数，就认为还有更多
      const hasMore = updateList.length < total

      console.log(`加载第${pageNum}页，新增${newList.length}条，总${updateList.length}/${total}，是否还有更多: ${hasMore}`)

      this.setData({
        list: updateList,
        total,
        hasMore,
        isLoading: false
      }, () => {
        this.getWrapHeight()
      })
    } catch (e) {
      this.setData({
        isLoading: false,
        loadLock: false // 出错时释放加载锁
      })
      my.alert({
        content: '加载失败，请重试'
      })
      console.error('加载失败:', e)
    }
  },
  async getSearchHeight() {
    const searchHeight = await getContainerHeight('.search-line-container')
    if (searchHeight) {
      this.setData({
        searchHeight
      })
    }
  },
  async getWrapHeight() {
    const scrollViewHeight = await getContainerHeight('.workOrderAudit_container')
    if (scrollViewHeight) {
      console.log('滚动容器高度:', scrollViewHeight)
      this.setData({
        scrollViewHeight
      })
    }
  },
  backToTop() {
    my.pageScrollTo({
      scrollTop: 0,
      duration: 300
    });
    this.setData({
      showBackTop: false
    });
  },
  searchInput(e) {
    this.setData({
      projectId: e.detail.value,
      'searchContent.id': e.detail.value
    })
  },
  handleSearch(val) {
    const searchContent = {
      id: val ? val : null,
    };

    this.setData({
      list: [],
      searchContent,
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        this.backToTop()
      })
    });
  },
  handleRangeOk(date, format, e) {
    console.log(format)
    this.setData({
      fixRange: format,
      'searchContent.fixRange': format // 将日期范围添加到搜索条件
    })
  },
  review(e) {
    const {
      item
    } = e.currentTarget.dataset
    my.navigateTo({
      url: `./audit/audit?item=${JSON.stringify(item)}`
    })
  },
  viewDetail(e) {
    console.log(e)
    my.navigateTo({
      url: `/pages/detail/detail?id=${e}`
    })
  },
  handleReset() {
    this.setData({
      rangeKey: this.data.rangeKey + 1,
      fixRange: null,
      projectId: '',
      searchContent: {},
      list: [],
      pageNum: 1,
      pageSize: 10,
      hasMore: true,
      isLoading: false,
      loadLock: false // 重置加载锁
    }, () => {
      this.getList().then(() => {
        this.backToTop()
      });
    });
  },
});